﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using VirtuOS.Components;
using VirtuOS.Components.Commands;
using System.Threading;
using System.Reflection;

namespace VirtuOS.Base
{
    class Boot
    {
        public void BootSequence()
        {
            Console.WriteLine("Initializing boot...");
            CheckFileSystem();
            CheckForUsers();
            UpdateCommands();
            Console.Clear();
            Terminal.AsciiArt();
            Services srv = new Services();
            Thread srvhost = new Thread(new ThreadStart(srv.Manager));
            srvhost.Start();
            while (!srvhost.IsAlive) ;
            Thread.Sleep(1);
        }

        private void CheckFileSystem()
        {
            Console.Write("\nChecking for filesystem...");
            if (!Directory.Exists("vdir"))
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.Write(" NOT FOUND\n");
                Console.ResetColor();
                Console.Write("Creating base file system...");
                Directory.CreateDirectory("vdir");
                Directory.CreateDirectory("vdir/tmp");
                Directory.CreateDirectory("vdir/etc");
                Directory.CreateDirectory("vdir/home");
                Directory.CreateDirectory("vdir/dev");
                Directory.CreateDirectory("vdir/mnt");
                Directory.CreateDirectory("vdir/var");
                Console.ForegroundColor = ConsoleColor.Green;
                Console.Write(" COMPLETE\n");
                Console.ResetColor();
            }
            else
            {
                Console.Write(" found!\n");
            }
            Environment.CurrentDirectory = VirtuOS.vdir_full;
        }

        private void CheckForUsers()
        {
            Console.Write("Checking for user accounts...");
            if (!Directory.Exists("etc/users"))
            {
                Console.WriteLine("\nNo users found... creating user: root\n");
                Directory.CreateDirectory("etc/users");
                UserHandler.AddUser("root");
                UserHandler.SetupUsers();
            }
            else
            {
                Console.Write(" found!\n");
            }
        }

        private void UpdateCommands()
        {
            Assembly assem = Assembly.GetExecutingAssembly();
            Type[] types = assem.GetTypes();
            foreach (Type t in types)
            {
                if (t.Namespace.Equals("VirtuOS.Components.Commands"))
                {
                    list.clist.Add(t.Name.ToString());
                }
            }
        }
    }
}
